﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Business;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Business.Opinions;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.JavaScript.JQuery;
using blackhouse.mojoPortalExtend;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;

namespace blackhouse.StareKino.Web {
    public partial class AddOpinion : OwnedNonCmsBasePage {

        #region Fields

        private float defaultCatValue = -1;
        private int reservationId;
        private Guid reservationGuid;
        private bool admin;

        private Factory factory = Factory.Instance();
        private IWebReservation reservation;
        private IOpinionCategory[] opinionCategories;
        private IApartmentGroup[] groups;

        #endregion

        #region Event Handlers

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            JQueryLibraries jql = new JQueryLibraries();
#if DEBUG
            jql.IncludeFileBasedOnJQuery("blackhouse.StareKino.Web.ClientScripts.add-opinion.js,blackhouse.StareKino.Web");
#else
            jql.IncludeFileBasedOnJQuery("blackhouse.StareKino.Web.ClientScripts.add-opinion.min.js,blackhouse.StareKino.Web");
#endif

            this.ReadInputParameters();
            this.SetInstance();
            this.PopulateControls();
            this.SetPage();
        }

        #endregion

        #region Methods

        private void ReadInputParameters() {
            Int32.TryParse(Request["addOpinion"], out this.reservationId);
            Guid.TryParse(Request["reservation"], out this.reservationGuid);
        }

        private void SetInstance() {
            this.opinionCategories = factory.GetOpinionCategory().GetCategories();
            this.admin = WebUser.IsAdminOrContentAdmin;
            if (reservationId > 0) {
                this.reservation = factory.GetWebReservation(reservationId);
                if (this.reservation.ReservationId != this.reservationId || this.reservation.Guid != this.reservationGuid || this.reservation.Status.MainId != 3) {
                    this.reservation = null;
                }
            }
            if (this.reservation == null && this.admin)
                this.groups = this.factory.GetApartmentGroup().GetAllApartmentTypes().OrderBy(a => a.ShortName).ToArray();
        }

        private void SetPage() {
            this.SetPageSettingsFromCms();
        }

        private void PopulateControls() {
            if (this.reservation != null) {
                this.pnlForm.Visible = true;
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DefaultOpinionCategoryValue"])) {
                    if (!float.TryParse(ConfigurationManager.AppSettings["DefaultOpinionCategoryValue"], NumberStyles.Float, CultureInfo.GetCultureInfo("en-US"), out this.defaultCatValue))
                        this.defaultCatValue = -1;
                }
                this.rptCategories.DataSource = this.opinionCategories;
                this.rptCategories.DataBind();

                this.txtPseudonim.Text = this.reservation.Client.FirstName;
                this.txtCountry.Text = "Polska";
                //this.Interviewer.ReservationId = this.reservation.ReservationId;
            }
            else {
                this.pnlNoData.Visible = true;
                if (this.admin)
                    this.PopulateAdminContent();
            }

        }

        private void PopulateAdminContent() {
            if (!IsPostBack) {
                this.pnlStillAddOpinion.Visible = true;
                this.ddlApartmentTypes.DataSource = this.groups;
                this.ddlApartmentTypes.DataBind();
            }
        }

        protected void ItemDataBound_rptCategories(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    IOpinionCategory category = e.Item.DataItem as IOpinionCategory;
                    Panel pnlAddCat = e.Item.FindControl("pnlCat") as Panel;
                    Label lblCatName = e.Item.FindControl("lblCatName") as Label;
                    TextBox txtCatVal = e.Item.FindControl("txtCatVal") as TextBox;

                    if (category != null && lblCatName != null && txtCatVal != null) {
                        lblCatName.Text = category.Name;
                        if (!string.IsNullOrEmpty(category.NameContinued))
                            lblCatName.Text += " (" + category.NameContinued + ")";
                        txtCatVal.Text = this.defaultCatValue.ToString("F1", CultureInfo.GetCultureInfo("en-US"));
                        txtCatVal.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                        txtCatVal.ID = "opinion-category-" + category.CategoryId;
                        pnlAddCat.Attributes.Add("catid", category.CategoryId.ToString());
                        pnlAddCat.Attributes.Add("data-panel", "categoryline");
                        txtCatVal.Attributes.Add("data-panel", "inputvalue");
                    }

                    break;
                default:
                    break;
            }
        }

        protected void bntSave_Click(object sender, EventArgs e) {


            IOpinion opinion = Factory.Instance().GetOpinion();
            opinion.InMinusOpinion = Request[this.txtInNinus.UniqueID];
            opinion.InPlusOpinion = Request[this.txtInPlus.UniqueID];
            opinion.PublishedDate = DateTime.Now;
            opinion.Publisher = new AuthorOpinion();
            opinion.Publisher.Category = Request[this.hdStayType.UniqueID].Replace("\r\n", "").Trim();
            opinion.Publisher.Country = Request[this.txtCountry.UniqueID + "_value"];
            if (string.IsNullOrEmpty(opinion.Publisher.Country))
                opinion.Publisher.Country = "POL";
            opinion.Publisher.FirstName = Request[this.txtPseudonim.UniqueID];
            opinion.Publisher.LastName = "";

            foreach (RepeaterItem item in this.rptCategories.Items) {
                TextBox tb = item.Controls.OfType<Panel>().First().Controls.OfType<TextBox>().First();
                if (tb != null) {
                    int categoryId;
                    float value;
                    if (
                        Int32.TryParse(tb.ID.ReplaceEx("opinion-category-", ""), out categoryId)
                        && float.TryParse(Request[tb.UniqueID], NumberStyles.Number, CultureInfo.GetCultureInfo("en-US"), out value)) {
                        opinion.AddOpinionDetailValue(categoryId, value);
                    }
                }
            }

            opinion.Save(this.GetUserId());
            if (this.admin)
                opinion.Publish(this.GetUserId());

            IOpinionToReservation otr = Factory.Instance().CreateOpinionToReservationTrans();
            otr.OpinionId = opinion.Id;
            otr.ReservationId = this.reservationId;
            otr.Save();

            this.pnlForm.Visible = false;
            this.pnlNoData.Visible = false;
            this.pnlOk.Visible = true;
        }

        private int GetUserId() {
            if (User.Identity.IsAuthenticated)
                return SiteUtils.GetCurrentSiteUser().UserId;
            else return 0;
        }

        protected void ddlApartmentTypes_SelectedIndexChanged(object sender, EventArgs e) {
            int groupId = 0;
            if (Int32.TryParse(Request[this.ddlApartmentTypes.UniqueID], out groupId)) {
                IOpinion opinion = this.factory.GetOpinion();
                this.reservationId = opinion.FindReservationToAddOpinion(groupId);
                if (this.reservationId > 0) {
                    this.reservation = this.factory.GetWebReservation(this.reservationId);
                    Response.Redirect(string.Format("/pages/addopinion.aspx?addOpinion={0}&reservation={1}", this.reservation.ReservationId, this.reservation.Guid));
                }
                else {
                    this.lblNoFreeReservation.Visible = true;
                }
            }
        }

        #endregion

    }
}